package com.jiwang.mail.util.result;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 沈伟峰
 */
public class JsonResult {

    private ResultStatus status;
    @JsonIgnore
    private List<String> messages;
    private Object data;

    private JsonResult() {
        this.status = null;
        this.messages = null;
        this.data = null;
    }

    private JsonResult(ResultStatus status, Object data, String... messages) {
        this.status = status;
        this.messages = new ArrayList<>();
        if (messages != null)
            this.messages.addAll(Arrays.asList(messages));
        this.data = data;
    }

    public static JsonResult newInstance() {
        return new JsonResult();
    }

    public static JsonResult newInstance(ResultStatus status) {
        return new JsonResult(status, null, (String[]) null);
    }

    public static JsonResult newInstance(ResultStatus status, String message, Object data) {
        return new JsonResult(status, data, message);
    }

    public static JsonResult newInstance(ResultStatus status, String[] messages, Object data) {
        return new JsonResult(status, data, messages);
    }

    public int getStatus() {
        return status.getCode();
    }

    public JsonResult setStatus(ResultStatus status) {
        this.status = status;
        return this;
    }

    public JsonResult setStatus(int code, String messageEN, String messageZH) {
        this.status = new ResultStatus(code, messageEN, messageZH);
        return this;
    }

    public List<String> getMessages() {
        return messages;
    }

    public JsonResult setMessages(List<String> messages) {
        this.messages = messages;
        return this;
    }

    public Object getData() {
        return data;
    }

    public JsonResult setData(Object data) {
        this.data = data;
        return this;
    }

    public String getMessage() {
        if (ObjectUtils.isEmpty(this.messages)) {
            return this.status.getMessage();
        }
        return this.messages.get(this.messages.size() - 1);
    }

    public JsonResult setMessage(String... message) {
        return this.addMessage(message);
    }

    public JsonResult addMessage(String... message) {
        try {
            if (this.messages == null)
                this.messages = Arrays.asList(message);
        } catch (Exception ignored) {
        }
        return this;
    }
}
